package com.aosiding.yygh.msm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aosiding.yygh.msm.service.MsmService;

import com.aosiding.yygh.msm.utils.ConstantPropertiesUtils;
import com.aosiding.yygh.msm.utils.RandomUtil;
import com.aosiding.yygh.vo.msm.MsmVo;
import com.aosiding.yygh.vo.order.OrderMqVo;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.mail.internet.NewsAddress;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class MsmServiceImpl implements MsmService {


    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送腾讯云短信1
//    @Override
//    public boolean send(String code, String phone){
//        try{
//            Credential cred = new Credential("*","*");//自己的腾讯key
//
//            HttpProfile httpProfile = new HttpProfile();
//            httpProfile.setEndpoint("sms.tencentcloudapi.com");
//
//            ClientProfile clientProfile = new ClientProfile();
//            clientProfile.setHttpProfile(httpProfile);
//
//            SmsClient client = new SmsClient(cred,"",clientProfile);
//            SendSmsRequest request = new SendSmsRequest();
//            String[] phone1 = {"+86"+phone};
//            String[] templateParamSet1 = {code};//验证码
//            request.setPhoneNumberSet(phone1);
//            request.setTemplateParamSet(templateParamSet1);
//            //必填:短信签名-可在短信控制台中找到
//            request.setSign("*");
//            //短信SdkAppid在 短信控制台 添加应用后生成的实际SdkAppid，示例如1400006666。
//            request.setSmsSdkAppid("*");
//            //必填:短信模板-可在短信控制台中找到
//            request.setTemplateID("*");
//            SendSmsResponse resp = client.SendSms(request);
//            return true;
//        }catch (Exception e){
//            e.printStackTrace();
//            return false;
//        }
//    }

    //发送腾讯云短信2
//    @Override
//    public boolean send(String phone, String code){
//        try{
//            Credential cred = new Credential("*","*");//自己的腾讯key
//
//            HttpProfile httpProfile = new HttpProfile();
//            httpProfile.setEndpoint("sms.tencentcloudapi.com");
//
//            ClientProfile clientProfile = new ClientProfile();
//            clientProfile.setHttpProfile(httpProfile);
//
//            SmsClient client = new SmsClient(cred,"",clientProfile);
//            SendSmsRequest request = new SendSmsRequest();
//            String[] phone1 = {"+86"+phone};
//            String[] templateParamSet1 = {code};//验证码
//            request.setPhoneNumberSet(phone1);
//            request.setTemplateParamSet(templateParamSet1);
//            //必填:短信签名-可在短信控制台中找到
//            request.setSign("*");
//            //短信SdkAppid在 短信控制台 添加应用后生成的实际SdkAppid，示例如1400006666。
//            request.setSmsSdkAppid("*");
//            //必填:短信模板-可在短信控制台中找到
//            request.setTemplateID("*");
//            SendSmsResponse resp = client.SendSms(request);
//            return true;
//        }catch (Exception e){
//            e.printStackTrace();
//            return false;
//        }
//    }


//    //邮箱验证码1
//    public boolean sendemail(String phone, HttpSession httpSession) {
//        //从redis获取验证码，如果获取获取到，返回ok
//        // key you  value 验证码
//        String code = redisTemplate.opsForValue().get(phone);
//        if(!StringUtils.isEmpty(code)) {
//            System.out.println("redis中已存在验证码，直接返回成功");
//            return true;
//        }
//        try {
//            SimpleMailMessage mailMessage = new SimpleMailMessage();
//
//            mailMessage.setSubject("尚医通 验证码");//主题
//            //生成随机数
//            code = RandomUtil.getSixBitRandom();
//
//            System.out.println(code);
//
//            //将随机数放置到session中
//            httpSession.setAttribute("phone",phone);
//            httpSession.setAttribute("code",code);
//
//            mailMessage.setText("您的尚医通注册/登录验证码是："+code);//内容
//
//            mailMessage.setTo(phone);//发给谁
//
//            mailMessage.setFrom(ConstantPropertiesUtils.EMAIL_NAME);//你自己的邮箱
//
//            mailSender.send(mailMessage);//发送
//
//            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
//
//            return  true;
//        }catch (Exception e){
//            e.printStackTrace();
//            return false;
//        }
//
//    }


    //邮箱验证码2
    public boolean sendemail(String phone) {
        //从redis获取验证码，如果获取获取到，返回ok
        // key you  value 验证码
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) {
            System.out.println("redis中已存在验证码，直接返回成功");
            return true;
        }
        try {
            MimeMessage mialMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mialMessage,true);

            helper.setSubject("尚医通 验证码");//主题
            //生成随机数
            code = RandomUtil.getSixBitRandom();

            System.out.println(code);

            helper.setText("您的尚医通注册/登录验证码是："+"<text style='color:red'>"+code+"</text>",true);//内容

            helper.addAttachment("奥斯丁.jpg",new File("C:\\Users\\AOSIDING\\Pictures\\Camera Roll\\084010-15332568109b5b.jpg"));

            helper.setTo(phone);//发给谁

//            helper.setFrom(ConstantPropertiesUtils.EMAIL_NAME);//你自己的邮箱,重载 增加头像
            helper.setFrom(ConstantPropertiesUtils.EMAIL_NAME, MimeUtility.encodeText("奥斯丁股份有限公司"));//你自己的邮箱

            mailSender.send(mialMessage);//发送

            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

            return  true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

    }
//    //发送阿里云手机验证码（个人无法申请阿里云短信，未测试）
//    @Override
//    public boolean send(String phone, String code) {
//        //判断手机号是否为空
//        if(org.springframework.util.StringUtils.isEmpty(phone)) {
//            return false;
//        }
//        //整合阿里云短信服务
//        //设置相关参数
//        DefaultProfile profile = DefaultProfile.
//                getProfile(ConstantPropertiesUtils.REGION_Id,
//                        ConstantPropertiesUtils.ACCESS_KEY_ID,
//                        ConstantPropertiesUtils.SECRECT);
//        IAcsClient client = new DefaultAcsClient(profile);
//        CommonRequest request = new CommonRequest();
//        //request.setProtocol(ProtocolType.HTTPS);
//        request.setMethod(MethodType.POST);
//        request.setDomain("dysmsapi.aliyuncs.com");
//        request.setVersion("2017-05-25");
//        request.setAction("SendSms");
//
//        //手机号
//        request.putQueryParameter("PhoneNumbers", phone);
//        //签名名称
//        request.putQueryParameter("SignName", "我的谷粒在线教育网站");
//        //模板code
//        request.putQueryParameter("TemplateCode", "SMS_180051135");
//        //验证码  使用json格式   {"code":"123456"}
//        Map<String,Object> param = new HashMap();
//        param.put("code",code);
//        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
//
//        //调用方法进行短信发送
//        try {
//            CommonResponse response = client.getCommonResponse(request);
//            System.out.println(response.getData());
//            return response.getHttpResponse().isSuccess();
//        } catch (ServerException e) {
//            e.printStackTrace();
//        } catch (ClientException e) {
//            e.printStackTrace();
//        }
//        return false;
//    }



    //mq发送短信，邮箱
    @Override
    public boolean send(MsmVo msmVo) {
        if (!StringUtils.isEmpty(msmVo.getPhone())){
            //String code = (String) msmVo.getParam().get("code");
            boolean isSend = this.send(msmVo.getPhone(), msmVo.getParam());
            return isSend;
        }
        return false;
    }

    private boolean send(String phone,Map<String,Object> param){
        try{
            //判断手机号是否为空
            if(org.springframework.util.StringUtils.isEmpty(phone)) {
                System.out.println(phone);
                return false;
            }

            //判断手机号是否为空
            if(org.springframework.util.StringUtils.isEmpty(param)) {
                System.out.println("参数里的"+param);
                return false;
            }

            MimeMessage mialMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mialMessage,true);

            helper.setSubject("预约信息通知");//主题


            //生成随机数
            String code = RandomUtil.getSixBitRandom();
            System.out.println(code);

            System.out.println("打印的"+param);

            System.out.println("病人名字："+param.get("name"));
            System.out.println("医生职称："+param.get("title"));
            System.out.println("退号时间："+param.get("quitTime"));
            System.out.println("安排日期："+param.get("reserveDate"));
            System.out.println("医事服务费："+param.get("amount"));

//            TODO 取key
//            Set<String> strings = param.keySet();
//            System.out.println(strings);

            //含验证码
//            helper.setText("预约信息通知："+"<text style='color:red'>"+code+"</text>",true);//内容

//          不含验证码<view></view>
            helper.setText(
                    "<view>预约挂号通知：</view>"
                    +"<p>"+param.get("name")+",您预定的日期为："+"<view style='color:red'>"+param.get("reserveDate")+"</view>,"
                            +"</p>"
                    +"<view>医生:"+param.get("title")+","
                            +"</view>"
                    +"<p>退号截止时间为:"+param.get("quitTime")+","
                            +"</p>"
                    +"<view>请及时微信支付挂号费"+param.get("amount")+"。"
                            +"</view>",true);//内容

            //helper.addAttachment("奥斯丁.jpg",new File("C:\\Users\\AOSIDING\\Pictures\\Camera Roll\\084010-15332568109b5b.jpg"));

            helper.setTo(phone);//发给谁

//            helper.setFrom(ConstantPropertiesUtils.EMAIL_NAME);//你自己的邮箱,重载 增加头像
            helper.setFrom(ConstantPropertiesUtils.EMAIL_NAME, MimeUtility.encodeText("奥斯丁股份有限公司"));//你自己的邮箱

            mailSender.send(mialMessage);//发送

            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}
